import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

# pyplot 中主要的函数

mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False


def plot_func():
    x = np.linspace(0.05, 10, 1000)
    y = np.cos(x)
    plt.plot(x, y, ls='-', lw=2, label='plot figure')
    plt.legend()
    plt.xlabel('x-axis')
    plt.ylabel('y-axis')
    plt.show()


def scatter_func():
    x = np.linspace(0.05, 10.0, 1000)
    y = np.random.rand(x.shape[0])
    #  c denotes the color of scatter
    plt.scatter(x, y, c='r', label='scatter figure')
    plt.legend()
    plt.show()


def lim_func():
    x = np.linspace(0.05, 10, 1000)
    y = np.random.rand(1000)
    plt.scatter(x, y, label='scatter figure')
    plt.legend()
    plt.xlim(0.05, 10)
    plt.ylim(0, 1)
    plt.show()


def grid_func():
    """
    绘制刻度线的网格线
    :return:
    """
    x = np.linspace(0.05, 10, 1000)
    y = np.sin(x)
    plt.plot(x, y, ls='-', lw=2, c='c', label='plot figure')
    plt.legend()
    # plt.grid(linestyle=':', color='r')
    # plt.grid(color='r')
    plt.grid(True)
    plt.show()


def axhline_axvline_func():
    x = np.linspace(0.05, 10, 1000)
    y = np.sin(x)

    plt.plot(x, y, ls='-', lw=2, c='c', label='plot figure')
    plt.legend()
    plt.axhline(y=0.0, c='r', ls='--', lw=2)
    plt.axvline(x=4.0, c='r', ls='--', lw=2)
    plt.show()


def axvspan_axhspan_func():
    x = np.linspace(0.05, 10, 1000)
    y = np.sin(x)
    plt.plot(x, y, ls='-', lw=2, c='c', label='plot figure')
    plt.legend()
    plt.axvspan(xmin=4.0, xmax=6.0, facecolor='y', alpha=0.3)
    plt.axhspan(ymin=0, ymax=0.5, facecolor='y', alpha=0.3)
    plt.show()


def annotate_func():
    x = np.linspace(0.05, 10, 1000)
    y = np.sin(x)
    plt.plot(x, y, ls='-.', lw=2, c='c', label='plot figure')
    plt.legend()
    plt.annotate('maximum',
                 xy=(np.pi / 2, 1.0),
                 xytext=(1.0 + np.pi / 2, .8),
                 weight='bold',
                 color='k',
                 arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='b'))
    plt.show()


def text_func():
    x = np.linspace(.05, 10, 1000)
    y = np.sin(x)
    plt.plot(x, y, ls='-.', lw=2, c='c', label='plot figure')
    plt.legend()
    plt.text(3.40, 0.09, 'y=sin(x)', weight='bold', color='b')
    plt.show()


def title_func():
    x = np.linspace(0.05, 10, 1000)
    y = np.sin(x)
    plt.plot(x, y, ls='-.', lw=2, c='c', label='plot figure')
    plt.legend()
    plt.title('y = sin(x)')
    plt.show()


def legend_func():
    x = np.linspace(0.05, 10, 1000)
    y = np.sin(x)
    plt.plot(x, y, ls='-.', lw=2, c='c', label='plot figure')
    plt.legend(loc='upper right')
    plt.show()


def demo_func():
    # define data
    x = np.linspace(0.5, 3.5, 100)
    y = np.sin(x)
    y1 = np.random.randn(100)

    # scatter figure
    plt.scatter(x, y1, c='0.25', label='scatter figure')
    # plot figure
    plt.plot(x, y, ls='--', lw=2, label='plot figure')

    # removing chartjunk
    # turn the top spine and the right spine off
    for spine in plt.gca().spines.keys():
        if spine == 'top' or spine == 'right':
            plt.gca().spines[spine].set_color('none')

    # turn bottom tick for x-axis on
    plt.gca().xaxis.set_ticks_position('bottom')
    # set tick_line position of bottom

    # leave left ticks for y-axis on
    plt.gca().yaxis.set_ticks_position('left')
    # set tick_line position of left

    # set axes limit
    plt.xlim(0.0, 4.0)
    plt.ylim(-3.0, 3.0)

    # set axes labels
    plt.ylabel('y_axis')
    plt.xlabel('x_axis')

    # set x,yaxis grid
    plt.grid(ls=':', color='r')

    # add a horizontal line across the axis
    plt.axhline(y=0.0, c='r', ls='--', lw=2)

    # add a vertical span across the axis
    plt.axvspan(xmin=1.0, xmax=2.0, facecolor='y', alpha=.3)

    # set annotating info
    plt.annotate('maximum', xy=(np.pi / 2, 1.0),
                 xytext=(0.15 + (np.pi / 2), 1.5), weight='bold', color='r',
                 arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='r'))
    plt.annotate('spines', xy=(0.75, -3),
                 xytext=(0.35, -2.25), weight='bold', color='b',
                 arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='b'))
    plt.annotate('', xy=(3.5, -2.98),
                 xytext=(3.6, -2.70),
                 arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='b'))

    # set text info
    plt.text(3.6, -2.70, "'|' is tickline", weight='bold', color='b')
    plt.text(3.6, -2.95, "3.5 is ticklabel", weight='bold', color='b')

    # set title
    plt.title('structure of matplotlib')

    plt.legend(loc='upper right')
    plt.show()


def bar_func(func):
    x = [i for i in range(1, 9)]
    y = [3, 1, 4, 5, 8, 9, 7, 2]
    labels = ['q', 'a', 'c', 'e', 'r', 'j', 'b', 'p']

    # create bar
    func(x, y, align='center', color='c', tick_label=labels, hatch='/')
    # set x,y_axis label
    plt.xlabel('箱子编号')
    plt.ylabel('箱子重量(kg)')
    plt.show()


def hist_func():
    boxWeight = np.random.randint(0, 10, 100)
    x = boxWeight
    bins = range(0, 11, 1)
    plt.hist(x, bins=bins, color='g', histtype='bar', rwidth=1, alpha=0.6)
    plt.xlabel('箱子重量 (kg)')
    plt.ylabel('销售个数 (个)')
    plt.show()


def pie_func():
    kinds = '简易箱', '保温箱', '行李箱', '密封箱'
    colors = ['#e41a1c', '#377eb8', '#4daf4a', '#984ea3']
    soldNums = [0.05, 0.45, 0.15, 0.35]
    plt.pie(soldNums,  # 不同成分的占比
            labels=kinds,  # 不同成分的标签
            autopct='%3.1f%%',  # 各部分占比的格式
            startangle=90,  # 从x轴逆时针旋转的角度
            colors=colors)
    plt.title('不同类型的箱子的销售数量占比')
    plt.show()


def polar_func():
    barSlices = 12
    theta = np.linspace(0.0, 2 * np.pi, barSlices, endpoint=False)
    r = 30 * np.random.rand(barSlices)  # 生成 维度是 (barSlices, ) 的 ndarray
    plt.polar(theta, r,
              color='chartreuse',
              linewidth=2,
              marker='*',
              mfc='b',
              ms=10)
    plt.show()


def scatter_3d_func():
    a = np.random.randn(100)
    b = np.random.randn(100)
    # colormap:RdYlBu
    # plt.scatter(a, b, s=np.power(10 * a + 20 * b, 2),
    #             c=np.random.rand(100),
    #             cmap=mpl.cm.RdYlBu,
    #             marker='o')
    plt.scatter(a, b, s=np.power(10 * a + 20 * b, 2),
                c=np.random.randn(100),
                cmap=mpl.cm.RdYlBu,
                marker='o')
    plt.grid()
    plt.show()


def stem_func():
    # x = np.linspace(0.5, 2 * np.pi, 20)
    # y = np.random.randn(20)
    x = [i for i in range(1, 5)]
    y = [5, 4, 1, -2]
    plt.stem(x, y, linefmt='-.', markerfmt='o', basefmt='-', use_line_collection=True)
    plt.show()


def boxplot_func():
    x = np.random.randn(1000)
    plt.boxplot(x)
    plt.xticks([1], ['随机数生成器 AlphaRM'])
    plt.ylabel('随机数值')
    plt.title('随机数生成器抗干扰能力的稳定性')
    plt.grid(axis='y', ls=':', lw=1, color='gray', alpha=0.4)
    plt.show()


def sigmoid(x):
    return 1 / (1 + np.exp(-x))


def errorbar_func():
    x = np.linspace(0.1, 0.6, 6)
    y = np.exp(x)
    # Note: yerr xerr 不是 callable, 是 float or list[float]
    plt.errorbar(x, y, fmt='bo:', yerr=0.2, xerr=0.02)
    plt.xlim(0, 0.7)
    plt.show()


if __name__ == '__main__':
    # plot_func()
    # scatter_func()
    # lim_func()
    # grid_func()
    # axhline_axvline_func()
    # axvspan_axhspan_func()
    # annotate_func()
    # text_func()
    # title_func()
    # legend_func()
    # demo_func()
    # bar_func(plt.bar)
    # hist_func()
    # pie_func()
    # polar_func()
    # scatter_3d_func()
    # stem_func()
    # boxplot_func()
    errorbar_func()
